package com.xtayfjpk.spring.security.test.service;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xtayfjpk.spring.security.test.domain.Customer;

@Service("myAclService")
@Transactional
public class ACLService {
	//@Resource
	private JdbcMutableAclService aclService;
	
	@PreAuthorize("hasRole('ROLE_ACL_ADMIN')")
	public void addPermission(Long id) {
		ObjectIdentity oi = new ObjectIdentityImpl(Customer.class, id);
		Permission p = BasePermission.READ;
		Sid sid = new PrincipalSid("zhangsan");
		MutableAcl acl = null;
		try {
			acl = (MutableAcl) aclService.readAclById(oi);
		} catch (Exception e) {
			acl = aclService.createAcl(oi);
		}
		
		// Now grant some permissions via an access control entry (ACE)
		acl.insertAce(acl.getEntries().size(), p, sid, true);
		aclService.updateAcl(acl);
	}
	
}
